package org.west.sky.frame.activiti.study.chapter8;

import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.util.CollectionUtils;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.List;

/**
 * author: chz
 * date: 2024/9/6
 * description: 查询待办任务
 */
public class RunDemo8_7 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo8_7 runDemo8_3 = new RunDemo8_7();
        runDemo8_3.runDemo();
    }

    private void runDemo() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");
        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter8/Chapter8_3.bpmn20.xml");
        System.out.println("流程定义ID:" + processDefinition.getId() + ",流程定义key:" + processDefinition.getKey());
        //根据流程定义id发起流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        System.out.println("发起流程实例成功，流程实例id:" + processInstance.getId());
        int i = 1;
        while (completeTask()) {
            System.out.println("完成任务处理第" + i++ + "次轮询");
        }

    }

    private boolean completeTask() {
        List<Task> zs = getTaskList("zs");
        List<Task> ls = getTaskList("ls");
        if (!CollectionUtils.isEmpty(zs)) {
            System.out.println("开始完成张三的任务");
            for (Task task : zs) {
                taskService.complete(task.getId());
                System.out.println("完成任务：" + task.getId());
            }
        }
        if (!CollectionUtils.isEmpty(ls)) {
            System.out.println("开始完成李四的任务");
            for (Task task : ls) {
                taskService.complete(task.getId());
                System.out.println("完成任务：" + task.getId());
            }
        }
        return !CollectionUtils.isEmpty(zs) || !CollectionUtils.isEmpty(ls);
    }

    private List<Task> getTaskList(String assignee) {
        System.out.println("查询用户【" + assignee + "】的待办任务");
        List<Task> list = taskService.createTaskQuery().taskAssignee(assignee).orderByTaskCreateTime().desc().list();
        if (CollectionUtils.isEmpty(list)) {
            System.out.println("没有查询到任务");
        } else {
            for (Task task : list) {
                System.out.println("任务id:" + task.getId() + ",任务名称：" + task.getName() + ",任务创建时间：" + sdf.format(task.getCreateTime()));
            }
        }
        return list;
    }


}
